package com.hpin.mlxteacher.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.BabyPagerAdapter;
import com.hpin.mlxteacher.adapter.ChildSchoolClassAdapter;
import com.hpin.mlxteacher.base.BaseFragment;
import com.hpin.mlxteacher.bean.ChildResult;
import com.hpin.mlxteacher.bean.SchoolClassReq;
import com.hpin.mlxteacher.child.ChildListActivity;
import com.hpin.mlxteacher.child.WorkActivity;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.DensityUtil;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.utils.LogUtil;

import java.util.List;

import de.greenrobot.event.EventBus;
//import com.umeng.analytics.MobclickAgent;

/**
 * 孩子fragment
 * Created by Administrator on 2015/7/15.
 */
public class ChildFragment extends BaseFragment implements View.OnClickListener {
    //    private List<ChildResult.childlist> childDatas;

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private BabyPagerAdapter pagerAdapter;
    private LocationMode mCurrentMode;
    private ViewPager vp_child;
    private MyLocationListenner myListener = new MyLocationListenner();
    // 定位相关
    private LocationClient mLocClient;
    //是否是第一次定位
    private boolean isFirstLoc = true;
    private SchoolClassReq classReq;
    //    private String currentClassId;
    private ChildSchoolClassAdapter schoolClassAdapter;
    private BitmapDescriptor mBitmap;
    private ChildResult childResult;
    private TextView tv_no_child;
    private TextView tv_title;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //设为第一次进入定位
        isFirstLoc = true;

        View childView = View.inflate(getActivity(), R.layout.fragment_child, null);

        // 构建Marker图标
        mBitmap = BitmapDescriptorFactory.fromResource(R.drawable.thumb);

        initWidget(childView);

        EventBus.getDefault().register(this);

        //如果没有选择班级 则获取班级信息
        if (CommonUtils.isNull(sp.getString(Constant.classId, ""))) {
            myClasses(null);
        } else {
            //选择了班级
            tv_title.setText(sp.getString(Constant.className, ""));
            getChildData(sp.getString(Constant.classId, ""));
        }

        return childView;

    }

    private void initWidget(View childView) {

        TextView tv_left = (TextView) childView.findViewById(R.id.tv_left);
        tv_title = (TextView) childView.findViewById(R.id.tv_title);
        TextView tv_right = (TextView) childView.findViewById(R.id.tv_right);
        tv_no_child = (TextView) childView.findViewById(R.id.tv_no_child);


        tv_left.setVisibility(View.VISIBLE);
        tv_right.setVisibility(View.VISIBLE);

        tv_left.setText(getResources().getString(R.string.child_work));
//        tv_title.setText(getResources().getString(R.string.rl_child));
        tv_right.setText(getResources().getString(R.string.child_list));

        vp_child = (ViewPager) childView.findViewById(R.id.vp_child);

        // 地图初始化
        mMapView = (MapView) childView.findViewById(R.id.bmapView);

        // 获取地图控件引用
        mBaiduMap = mMapView.getMap();

        //点击地图其它部位 隐藏window
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {

            @Override
            public boolean onMapPoiClick(MapPoi arg0) {
                return false;
            }

            @Override
            public void onMapClick(LatLng arg0) {
                if (mBaiduMap != null)
                    mBaiduMap.hideInfoWindow();
            }
        });

        //点击marks显示孩子的具体信息
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker arg0) {

                showBabyLocationInfo(arg0);
                LogUtil.e("tag", "======  OnMarkerClick  ======");
                return false;
            }

        });

        //隐藏缩放按钮
        View zoom = null;
        for (int i = 0; i < mMapView.getChildCount(); i++) {
            View child = mMapView.getChildAt(i);
            if (child instanceof ZoomControls) {
                zoom = child;
                break;
            }
        }

        if (zoom != null)
            zoom.setVisibility(View.INVISIBLE);

        getMyLocation();

        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);
        tv_title.setOnClickListener(this);

    }

    /**
     * 点击孩子定位点获取孩子的信息
     *
     * @param marker
     */
    private void showBabyLocationInfo(Marker marker) {

        TextView view = (TextView) View.inflate(getActivity(), R.layout.layout_child_location_bg, null);

//        TextView view = new TextView(getActivity());
//        view.setPadding(5, 5, 5, 5);
//        view.setGravity(Gravity.CENTER);
//        view.setBackgroundResource(R.drawable.icon_baby_loc_bg);

//        view.setImageResource(R.drawable.icon_baby_loc_bg);

        InfoWindow myInfoWindow = new InfoWindow(view, marker.getPosition(), -DensityUtil.px2dip(getActivity(), 60));
        mBaiduMap.showInfoWindow(myInfoWindow);

        ChildResult.childlist childlist = (ChildResult.childlist) marker.getExtraInfo().get("info");

        //设置孩子姓名
        if (childlist != null) {
            view.setText(childlist.name);
        }

    }

    /**
     * 获取到我的当前位置
     */
    private void getMyLocation() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_center_point_my);
        mCurrentMode = LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
        //定位的点击事件
        mBaiduMap.setOnMyLocationClickListener(new BaiduMap.OnMyLocationClickListener() {

            @Override
            public boolean onMyLocationClick() {

//                LogUtil.e("tag", "我的位置的点击:" + "myLatitude:" + mApplication.myLatitude
//                 + "myLongitude:" + mApplication.myLongitude);

                LatLng latLng = new LatLng(mApplication.myLatitude, mApplication.myLongitude);
                showMyLocationInfo(latLng);
                return false;
            }
        });

        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(10000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

    private TextView myLocatView;

    /**
     * 显示我的位置
     *
     * @param latLng
     */
    private void showMyLocationInfo(LatLng latLng) {

        if (myLocatView == null) {
            myLocatView = new TextView(getActivity());
            myLocatView.setGravity(Gravity.CENTER);
            myLocatView.setBackgroundResource(R.drawable.ic_mylocation_bg);
        }
//        myLocatView.setText("我的位置");
        InfoWindow myInfoWindow = new InfoWindow(myLocatView, latLng, 10);
        mBaiduMap.showInfoWindow(myInfoWindow);

    }


    /**
     * 创建孩子定位点
     *
     * @param childDatas
     */
    private void createChildMarks(List<ChildResult.childlist> childDatas) {

        if (mBaiduMap != null)
            mBaiduMap.clear();
        //根据服务器返回的点的集合个数,创建多少个点
        for (int i = 0; i < childDatas.size(); i++) {

            //如果没有手表信息,继续循环
            if (childDatas.get(i).device == null) {
                continue;
            }

            //如果没有坐标信息,继续循环
            if (CommonUtils.isNull(childDatas.get(i).device.stuLat) || CommonUtils.isNull(childDatas.get(i).device.stuLng)
                    || !CommonUtils.isStr2Dou(childDatas.get(i).device.stuLat) || !CommonUtils.isStr2Dou(childDatas.get(i).device.stuLng))
                continue;

            //创建点
            LatLng point = new LatLng(Double.parseDouble(childDatas.get(i).device.stuLat), Double.parseDouble(childDatas.get(i).device.stuLng));
            MarkerOptions option = new MarkerOptions().position(point).icon(mBitmap).zIndex(5);
            Marker marker = (Marker) (mBaiduMap.addOverlay(option));

            Bundle bundle = new Bundle();
            bundle.putSerializable("info", childDatas.get(i));
            marker.setExtraInfo(bundle);

            // 定位到该点
            moveToLocation(point);

        }

    }

    /**
     * 定位到指定的点
     *
     * @param point 定位的点
     */
    private void moveToLocation(LatLng point) {
        // 定位到该点
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(point);
        mBaiduMap.setMapStatus(u);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                //工作

                Intent intent = new Intent(getActivity(), WorkActivity.class);
                getActivity().startActivity(intent);

                break;
            case R.id.tv_right:
                //列表
                Intent mIntent = new Intent(getActivity(), ChildListActivity.class);
                startActivity(mIntent);
//                EventBus.getDefault().post(childResult);
                break;

            case R.id.tv_title:  //选择班级

                if (classReq != null) {
                    showPup(classReq, v);//已经加载过班级信息 直接弹出提示
                } else
                    myClasses(v);//未加载过班级信息, 先获取班级信息

                break;
        }
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            mApplication.myLatitude = location.getLatitude();
            mApplication.myLongitude = location.getLongitude();

            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;

                try {
                    LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);

                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

        }

    }

    /**
     * 孩子详情的点击事件,点击后地图定位到该孩子的位置
     *
     * @param child
     */
    public void onEventMainThread(ChildResult.childlist child) {

        if (child != null && child.device != null) {

//            LogUtil.e("tag", "孩子详情的点击事件" + child.name + ",stuLng:"+child.device.stuLng
//             + ",stuLat:" + child.device.stuLat);

            //如果没有坐标信息则return
            if (CommonUtils.isNull(child.device.stuLat) || CommonUtils.isNull(child.device.stuLng)
                    || !CommonUtils.isStr2Dou(child.device.stuLat) || !CommonUtils.isStr2Dou(child.device.stuLng))
                return;

            //有坐标信息
            LatLng point = new LatLng(Double.parseDouble(child.device.stuLat), Double.parseDouble(child.device.stuLng));
            moveToLocation(point);

        }

    }


    @Override
    public void onDestroy() {
        if (mMapView != null)
            mMapView.onDestroy();

        EventBus.getDefault().unregister(this);

        super.onDestroy();

//        mApplication.cancelPendingRequests(getClass().getName());

    }

    @Override
    public void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        if (mMapView != null)
            mMapView.onResume();

//        MobclickAgent.onPageStart(getClass().getName()); //统计页面
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mMapView != null)
            mMapView.onPause();

    }

    /**
     * 获取孩子数据
     */
    private void getChildData(String classId) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("lat", mApplication.myLatitude);
        j.put("lon", mApplication.myLongitude);
        j.put("classId", classId);

        HttpUtil.setPostRequest("刷新中...", getActivity(), Constant.WEB_ROOT + Constant.GETCHILDERNANDWATCH,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {
                            childResult = JSONObject.parseObject(str, ChildResult.class);
                            if (childResult.code == Constant.SUCCESS) {

                                List<ChildResult.childlist> childDatas = childResult.data;

                                if (childDatas == null)
                                    return;

                                //班级 没有 学生信息
                                if (childDatas.size() == 0) {
                                    tv_no_child.setVisibility(View.VISIBLE);
                                    tv_no_child.setText("未查询到该班级学生信息");
                                    vp_child.setVisibility(View.INVISIBLE);
                                    return;
                                }

                                tv_no_child.setVisibility(View.INVISIBLE);
                                vp_child.setVisibility(View.VISIBLE);
                                //设置viewpager数据
                                pagerAdapter = new BabyPagerAdapter(getActivity(), childDatas);
                                vp_child.setAdapter(pagerAdapter);

                                vp_child.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                    @Override
                                    public void onPageScrolled(int i, float v, int i1) {
                                    }

                                    @Override
                                    public void onPageSelected(int i) {

                                        chooseLocation(i);

                                    }

                                    @Override
                                    public void onPageScrollStateChanged(int i) {
                                    }
                                });


                                //创建所有孩子的定位点
                                createChildMarks(childDatas);

                            } else {
                                showToast(Constant.showErrorMsg(childResult.code, getActivity()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }
                    }
                }, new HttpUtil.FailListener() {
                    @Override
                    public void setOnFailListener() {
                        tv_no_child.setVisibility(View.VISIBLE);
                        tv_no_child.setText("网络错误");
                        vp_child.setVisibility(View.INVISIBLE);
                    }
                });
    }


    private void chooseLocation(int i) {

        if (childResult != null && childResult.data != null) {

            ChildResult.childlist childlist = childResult.data.get(i);

            if (childlist != null && childlist.device != null) {

                //如果没有坐标信息则return
                if (CommonUtils.isNull(childlist.device.stuLat) || CommonUtils.isNull(childlist.device.stuLng)
                        || !CommonUtils.isStr2Dou(childlist.device.stuLat) || !CommonUtils.isStr2Dou(childlist.device.stuLng))
                    return;

                //有坐标信息
                LatLng point = new LatLng(Double.parseDouble(childlist.device.stuLat), Double.parseDouble(childlist.device.stuLng));
                moveToLocation(point);
            }

        }
    }

    /**
     * 获取我的班级
     */
    private void myClasses(final View v) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        HttpUtil.setPostRequest("获取班级中...", getActivity(), Constant.WEB_ROOT + Constant.MYCLASSES,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            classReq = JSONObject.parseObject(str, SchoolClassReq.class);

                            if (classReq.code == Constant.SUCCESS) {

                                if (classReq.data != null && classReq.data.size() > 0) {

                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString(Constant.classId, classReq.data.get(0).id);
                                    edit.putString(Constant.className, classReq.data.get(0).nickName);
                                    edit.apply();

                                    if (v != null) {
                                        showPup(classReq, v);
                                    } else {    //第一次进入 默认选择第一个
                                        tv_title.setText(classReq.data.get(0).nickName);
                                        getChildData(classReq.data.get(0).id);
                                    }
                                } else {
                                    showToast("未查询到班级信息");
                                }

                            } else
                                showToast(Constant.showErrorMsg(classReq.code, getActivity()));

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

    /**
     * 弹出选择popu的窗口
     *
     * @param classReq
     * @param v
     */
    private void showPup(final SchoolClassReq classReq, View v) {

        //先把图标改为箭头向上的
        tv_title.setBackgroundResource(R.drawable.choose_class_up);

        View popuView = View.inflate(getActivity(), R.layout.layout_child_choose_class, null);

        final PopupWindow classDialog = new PopupWindow(popuView,
                DensityUtil.dip2px(getActivity(), 100), ViewGroup.LayoutParams.WRAP_CONTENT);
        classDialog.setOutsideTouchable(true);
        classDialog.setFocusable(true);
        classDialog.setBackgroundDrawable(new BitmapDrawable());
        //x y   DensityUtil.dip2px(getActivity(), 5)
//        classDialog.showAsDropDown(v, 0, DensityUtil.dip2px(getActivity(), 5)); //0 0  x y 轴的偏移量
        classDialog.showAsDropDown(v, 0, 0); //0 0  x y 轴的偏移量
//        //屏幕变暗
//        changeScreen(0.5f);

        ListView lv_class = (ListView) popuView.findViewById(R.id.lv_class);

//        temList = classReq.data;
        schoolClassAdapter = new ChildSchoolClassAdapter(getActivity(), classReq.data);

        lv_class.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //选择班级
                if (classReq != null && classReq.data != null && classReq.data.size() > 0) {
//                    currentClassId = classReq.data.get(i).id;
                    getChildData(classReq.data.get(i).id);
                    tv_title.setText(classReq.data.get(i).nickName);

                    //保存班级名称和id
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString(Constant.classId, classReq.data.get(i).id);
                    edit.putString(Constant.className, classReq.data.get(i).nickName);
                    edit.apply();

                }

                if (classDialog != null && classDialog.isShowing())
                    classDialog.dismiss();

            }
        });

        classDialog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //把图标改为箭头向下的
                tv_title.setBackgroundResource(R.drawable.choose_class_down);
            }
        });

        lv_class.setAdapter(schoolClassAdapter);

//        classDialog.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
////                changeScreen(1f);
//            }
//        });
    }

//    private void changeScreen(float f) {
//        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
//        lp.alpha = f;
//        lp.dimAmount = f;
//        getActivity().getWindow().setAttributes(lp);
//    }

}
